import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class AuthToken {
    private static final long DEFAULT_EXPIRED_TIME_INTERVAL = 3 * 1000; //3000 ms
    private static final String SEPARATE = "@";

    private String token;
    private long createTimeStamp;
    private long CheckTimeInterval = DEFAULT_EXPIRED_TIME_INTERVAL;
    public AuthToken(String token, long timestamp){
        this.token = token;
        this.createTimeStamp = timestamp;
    }

    public AuthToken(String token, long timestamp,int CheckTimeInterval){
         this(token,timestamp);
         this.CheckTimeInterval = CheckTimeInterval;
    }

    public String getToken() {
        return this.token;
    }
    //方法区
    public boolean isExpired(){
        return createTimeStamp + CheckTimeInterval < System.currentTimeMillis();
    }

    public static AuthToken generate(String baseUrl, long createTime, Map<String, Object> param) {
        // param =appID+password 组合
        Set<String> keys = param.keySet();
        if(keys.size() == 1){
            Iterator<String> key = keys.iterator();
            while(key.hasNext()){
                String appID = key.next();
                String pwd = (String)param.get(appID);
                return generate(baseUrl,appID,createTime,pwd);
            }
        }
        return null;
    }

    public static AuthToken generate(String originalUrl, String appId, long timestamp, String password) {
        String token = generateTokenString(originalUrl, appId, timestamp, password);
        AuthToken authToken = new AuthToken(token, timestamp);
        return authToken;
    }



    public static String generateTokenString(String originalUrl, String appId, long timestamp, String password) {
        StringBuffer sb = new StringBuffer(originalUrl);
        sb.append(SEPARATE).append(appId);
        sb.append(SEPARATE).append(timestamp);
        sb.append(SEPARATE).append(password);
        return MD5Utils.getMD5String(sb.toString());
    }

    public boolean match(AuthToken authToken) {
        return this.token.equals(authToken.getToken());
    }
}
